<?php
use Illuminate\Database\Capsule\Manager as DB;

#[新闻资讯管理]
class NewsController extends AcommonController
{

    public function init() {
        $this->table = 'news';
        $this->model = new \app\modules\Admin\models\newsModel();
        $this->primaryKey = 'id';
        parent::init();
    }

    #[新闻资讯列表]
    public function indexAction($returnData = FALSE)
    {
        if($this->isPost()){
            $query = $this->model->with(['oper']);
            $keywords = $this->get('keywords', '');
            if(!empty($keywords)){
                $query = $query->where(function ($searchQuery) use($keywords){
                    $searchQuery->where($this->primaryKey, $keywords)->orWhere('title', 'like', "%{$keywords}%");
                });
            }
            $total = $query->count();
            $sort = $this->get('sort', 'sortorder');
            $order = $this->get('order', 'desc');
            $query = $query->orderBy('recommend', 'desc')->orderBy($sort, $order)->orderBy($this->primaryKey, 'DESC');
            $page = $this->get('page');

            if (!empty($page)) {
                $limit = $this->get('rows', 10);
                $offset = ($page - 1) * $limit;
                $query = $query->offset($offset)->limit($limit);
            }
            $rows = $query->get();
            json(['total' => $total, 'rows' => $rows]);
        }else{
            return parent::indexAction($returnData); // TODO: Change the autogenerated stub
        }
    }

    #[添加新闻资讯]
    public function addAction()
    {
        if($this->isPost()) {
            try {
                $rows = $this->postData;
                if(empty($rows['title'])){
                    throw new Exception('标题 没有填写', 30001);
                }
                if(empty($rows['content'])){
                    throw new Exception('内容 没有填写', 30001);
                }
                $content = $rows['content'];
                unset($rows[$this->primaryKey], $rows['created_at'], $rows['oper_id'], $rows['cat_id']);
                $this->cleanColumn($rows);
                $rows['oper_id'] = $this->auth->user_id;
                $rows['created_at'] = timestamp();
                $rows['updated_at'] = $rows['created_at'];
                $res = DB::transaction(function () use ($rows, $content){
                    $news_id = \app\modules\Admin\models\newsModel::query()->insertGetId($rows);
                    if($news_id){
                        newscontentModel::query()->insert(['news_id'=>$news_id, 'content'=>$content]);
                    }
                    return $news_id;
                });
                if($res){
                    ret(0, '新增新闻成功！');
                }else{
                    ret(1, '新增新闻失败');
                }
            } catch (Exception $e) {
                ret(2, (($e->getCode()=== 30001)?$e->getMessage():'新增新闻出错！'));
            }
        }else{
            $dataset = $this->getTableColumn($this->table);
            unset($dataset['id'], $dataset['cat_id'], $dataset['oper_id'], $dataset['created_at'], $dataset['updated_at']);
            $this->_view->assign('fontType', json_encode(\app\modules\Admin\models\newsModel::getAllFontType()));
            $this->_view->assign('dataset', json_encode($dataset));
            $this->_view->display( strtolower($this->controller) . '/edit.html');
        }
    }

    #[编辑新闻资讯]
    public function editAction()
    {
        if($this->isPost()) {
            try {
                $id = $this->get('id', 0);
                $news = \app\modules\Admin\models\newsModel::query()->findOrFail($id);
                $rows = $this->postData;
                if(empty($rows['title'])){
                    throw new Exception('标题 没有填写', 30001);
                }
                if(empty($rows['content'])){
                    throw new Exception('内容 没有填写', 30001);
                }
                $content = $rows['content'];
                unset($rows[$this->primaryKey], $rows['created_at'], $rows['oper_id'], $rows['cat_id']);
                $this->cleanColumn($rows);
                $rows['updated_at'] = timestamp();
                DB::transaction(function () use ($id, $rows, $content){
                    if(\app\modules\Admin\models\newsModel::query()->where('id', $id)->update($rows)){
                        newscontentModel::query()->where('news_id', $id)->update(['content'=>$content]);
                    }else{
                        throw new Exception('修改新闻失败', 30001);
                    }
                });
                unset($id, $news, $rows, $content);
                ret(0, '修改新闻成功！');
            } catch (Exception $e) {
                ret(2, (($e->getCode()=== 30001)?$e->getMessage():'修改新闻出错！'));
            }
        }else{
            $query = $this->model;
            $id	= $this->get($this->primaryKey, 0);
            if($query->where($this->primaryKey,'=',$id)->doesntExist()){
                throw new Exception("新闻不存在");
            }
            $news = $query->with(['news_content'])->where($this->primaryKey,'=',$id)->first();
            if ($news->news_content){
                $dataset = $news->toArray();
                $dataset['content'] = $news['news_content']['content'];
                unset($dataset['news_content'],$dataset['cat_id'], $dataset['oper_id'], $dataset['created_at'], $dataset['updated_at']);
            }else{
                throw new Exception("新闻内容不存在");
            }
            $this->_view->assign('fontType', json_encode(\app\modules\Admin\models\newsModel::getAllFontType()));
            $this->_view->assign('dataset', json_encode($dataset));
            $this->_view->display( strtolower($this->controller) . '/edit.html');
        }
    }

    #[删除新闻资讯]
    public function deleteAction()
    {
        $id = $this->get('id', 0);
        try {
            if(empty($id) || !is_numeric($id) || $id <= 0){
                throw new Exception('参数出错', 30001);
            }
            if ($this->model->where($this->primaryKey, '=', $id)->doesntExist()) {
                throw new Exception('新闻不存在', 30001);
            }
            DB::transaction(function () use ($id){
                if ($this->model->where($this->primaryKey, '=', $id)->delete()) {
                    newscontentModel::query()->where('news_id', $id)->delete();
                }else{
                    throw new Exception('删除新闻失败', 30001);
                }
            });
            ret(0, '删除新闻成功！');
        } catch (Exception $e) {
            ret(2, (($e->getCode()=== 30001)?$e->getMessage():'删除新闻出错！'));
        }

    }
}
